package algorithm.arithmetic.算法求和2;

/**
 * @author xinchen by 2016/11/25
 * @version 1.0
 */
public class Solution {


    // 质数（prime number）又称素数。质数定义为在大于1的自然数中，除了1和它本身以外不再有其他因数的数称为质数。
    // 算法求一个正整数的质因数之和
    public static void main(String[] args) {
        int nowPrime = 2;
        int num = Integer.parseInt(args[0]);
        int sum = 0;
        int sqrt = (int) Math.sqrt(num);
        while (nowPrime <= num) {
            if (nowPrime > sqrt) {
                sum += num;
                num = 1;
            } else if (num % nowPrime == 0) {
                sum += nowPrime;
                num = num / nowPrime;
            } else {
                nowPrime = getNextPrime(nowPrime);
            }
        }
        System.out.println(sum);
    }

    private static int getNextPrime(int min) {
        for (int i = min + 1; ; i++) {
            if (isPrime(i)) {
                return i;
            }
        }
    }

    private static boolean isPrime(int num) {
        int max = (int) Math.sqrt(num);
        for (int i = 2; i <= max; i++) {
            if (num % i == 0) {
                return false;
            }
        }
        return true;
    }
}
